package sum.book.common.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import sum.book.common.web.filter.HeaderValueFilter;

import javax.annotation.Resource;

/**
 * @Auther: ZhangGN
 * @Description: 资源服务器搭建
 * @Date 2022/11/18 15:50
 **/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Value(value = "${spring.application.name}")
    public String RESOURCE_ID;

    @Resource
    ResourceServerTokenServices resourceServerTokenServices;

    @Resource
    HeaderValueFilter headerValueFilter;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .addFilterBefore(headerValueFilter, BasicAuthenticationFilter.class)
                .authorizeRequests()//得到SpringSecurity接管的请求
                .antMatchers("/api/user/login").permitAll() // 表示 所有请求中 只要匹配了 /system/api/user/login 这个请求 则 放行 不去校验是否有Token
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID)//资源 id
                .tokenServices(resourceServerTokenServices)
                .stateless(true);
    }


}
